{% extends 'base/base.html' %}
{% load static %}
{% block css %}

<link href="/static/assets/css/font-awesome.min.css" rel="stylesheet"/>
<link href="/static/assets/css/jquery-ui-1.10.3.full.min.css" rel="stylesheet"/>
<link href="/static/assets/css/datepicker.css" rel="stylesheet"/>
<link href="/static/assets/css/ui.jqgrid.css" rel="stylesheet"/>
<link href="/static/assets/css/ace.min.css" rel="stylesheet"/>
<link href="/static/assets/css/ace-rtl.min.css" rel="stylesheet"/>
<link href="/static/assets/css/ace-skins.min.css" rel="stylesheet"/>
    <style type="text/css">
        .search{
            margin-left: 950px;
        }
        .export{
            float: left;
        }
        #excel,#allexcel{
            background: rgb(244,244,244);
            border: #cecece solid 1px;

        }
    </style>
{% endblock %}
{% block content %}
        <div class="row">
            <div class="col-md-12 col-sm-12 col-xs-12">
                <div class="x_panel">
                    <div class="x_title">
                        <h2>街道乡镇级基本信息记录</h2>
                        <div class="clearfix"></div>
                    </div>
                    <div class="export">
 {#                      <input type="BUTTON" id="dedata" value="删除所选记录" />#}
                        <input type="BUTTON" id="excel" value="导出所选记录" />
                        <input type="BUTTON" id="allexcel" value="导出全部记录" />
                   </div>
                    <div class="search">
                            <label>搜索:
                                <input type="text" value="" id="search">
                            </label>
                    </div>
                    <table id="grid-table"></table>
                    <div id="grid-pager"></div>

                </div>
            </div>
        </div>
{% endblock %}
{% block js %}
<script src="/static/assets/js/ace-extra.min.js"></script>
<script src="/static/assets/js/jqGrid/jquery.jqGrid.min.js"></script>
<script src="/static/assets/js/jqGrid/i18n/grid.locale-en.js"></script>
<script src="/static/assets/js/ace-elements.min.js"></script>
<script src="/static/assets/js/ace.min.js"></script>
<script src="/static/assets/js/xlsx.full.min.js"></script>

<script type="text/javascript">


        var excelTitle = "{{ excelTitle }}"
        excelTitle = excelTitle.replace(/\&quot;/g, '\"');
        excelTitle = JSON.parse(excelTitle);


        jQuery(function ($) {
            var grid_selector = "#grid-table";
            var pager_selector = "#grid-pager"

            var item_selected = []

            jQuery(grid_selector).jqGrid({
                datatype: "json",
                url: "/wenjuan/wenjuan_hunan_solve/no11/",
                mtype: 'POST',
                height: 600,
                width: 400,
                colNames: ['记录编号', '填表人签名', '填表人联系电话', '填表人填写日期'],
                colModel: [{name: "_id", id: "_id", width: 100},
                    {name: "填表人签名", id: "填表人签名", width: 100},
                    {name: "填表人联系电话", id: "填表人联系电话", width: 100},
                    {name: "填表人填写日期", id: "填表人填写日期", width: 100}
                ],
                pager: pager_selector, //分页工具栏
                altRows: true,
                rowNum: 50, //每页显示记录数
                viewrecords: true, //是否显示行数
                rowList: [50, 100, 200, 1000, 2000], //可调整每页显示的记录数
                multiselect: true, //是否支持多选
                loadComplete: function () {
                    var table = this;
                    setTimeout(function () {
                        updatePagerIcons(table);
                        enableTooltips(table);
                    }, 0);
                },
                caption: "街道乡镇级基本信息记录",
                autowidth: true,
                //选中翻页取消修改
                onSelectRow: function (rowid, status) {
                    let selected = $(grid_selector).jqGrid("getRowData", rowid);
                    if (status) { // 每一次取消选中时，将该行id添加到SelectList中
                        if (item_selected.indexOf(selected['_id']) == -1) {//每一次勾选时，检查该行是否在item_selected中，
                            //不在则进行添加
                            item_selected.push(selected['_id']);
                        }
                    } else {
                        if (item_selected.indexOf(selected['_id']) > -1) {//每一次取消勾选时，检查该行是否在item_selected中，
                            //若在，则在item_selected中删除该记录
                            item_selected.splice($.inArray(selected['_id'], item_selected), 1)
                        }
                    }
                },
                onSelectAll: function (aRowids, status) {
                    if (status) {
                        for (let i = 0; i < aRowids.length; i++) {
                            let selected = $(grid_selector).jqGrid("getRowData", aRowids[i]);
                            if (item_selected.indexOf(selected['_id']) == -1) {//每一次勾选时，检查该行是否在item_selected中，
                                //不在则进行添加
                                item_selected.push(selected['_id']);
                            }
                        }
                    } else {
                        for (let i = 0; i < aRowids.length; i++) {
                            let selected = $(grid_selector).jqGrid("getRowData", aRowids[i]);
                            if (item_selected.indexOf(selected['_id']) > -1) {//每一次勾选时，检查该行是否在item_selected中，
                                //若在，则在item_selected中删除该记录
                                item_selected.splice($.inArray(selected['_id'], item_selected), 1)
                            }
                        }
                    }
                },
                gridComplete: function () {//翻页时根据数组中的记录更新列表中的选中行
                    let ids = $(grid_selector).jqGrid('getDataIDs');
                    let select_ids = []
                    for (var i = 0; i < ids.length; i++) {
                        let row_id = $(grid_selector).jqGrid("getRowData", ids[i]);
                        if ((item_selected.indexOf(row_id['_id']) > -1)) {
                            $(grid_selector).jqGrid('setSelection', ids[i], true);
                        }
                    }

                },
                //选中翻页取消修改
            });

            //switch element when editing inline
            function aceSwitch(cellvalue, options, cell) {
                setTimeout(function () {
                    $(cell).find('input[type=checkbox]')
                        .wrap('<label class="inline" />')
                        .addClass('ace ace-switch ace-switch-5')
                        .after('<span class="lbl"></span>');
                }, 0);
            }

            //navButtons
            jQuery(grid_selector).jqGrid('navGrid', pager_selector,
                { 	//navbar options
                    edit: false,
                    {#editicon : 'icon-pencil blue',#}

                    add: false,
                    {#addicon : 'icon-plus-sign purple',#}

                    del: false,
                    delicon: 'icon-trash red',

                    search: false,
                    searchicon: 'icon-search orange',

                    refresh: true,
                    refreshicon: 'icon-refresh green',

                    view: false,
                    viewicon: 'icon-zoom-in grey',
                }
            );

            $("#dedata").click(function () {
                var gr = jQuery(grid_selector).jqGrid('getGridParam', 'selarrrow'); //获取选中的行集合
                var selectD = ''; //用户选择的需要删除的数据
                if (gr.length != 0) {
                    for (var i = 0; i < gr.length; i++) { //获取选择行的数据标识
                        var ret = $(grid_selector).jqGrid("getRowData", gr[i]);
                        selectD = selectD + ret['_id'] + ",";
                    }
                    for (var i = 0, l = gr.length; i < l; i++) { //保证同时可以删除多行
                        $(grid_selector).jqGrid("delRowData", gr[0]);
                    }
                    $.ajax({
                        url: "{% url 'DelWenjuan1_cgx' %}",
                        type: "POST",
                        data: {
                            selectRaw: selectD,
                            csrfmiddlewaretoken: '{{ csrf_token }}'
                        },
                        success: function (data) {
                            ;
                        }
                    })
                } else {
                    alert("请选择需要删除的行!");
                }
            });
            $("#excel").click(function () {
                //选中翻页取消修改
                var selectD = ''; //用户选择的需要导出的数据
                if (item_selected.length != 0) {
                    for (var i = 0; i < item_selected.length; i++) { //保证同时可以删除多行
                        selectD = selectD + item_selected[i] + ",";
                    }
                    //选中翻页取消修改
                    $.ajax({
                        url: "/wenjuan/ExportWenjuan/{{ request.user }}/no11/",
                        type: "POST",
                        data: {
                            selectRaw: selectD,
                            csrfmiddlewaretoken: '{{ csrf_token }}'
                        },
                        success: function (data) {
                            var aoa = [];
                            aoa.push(excelTitle);
                            for (var i = 0; i < JSON.parse(data).length; i++) {
                                aoa.push(JSON.parse(data)[i])
                            }

                            exportSpecialExcel(aoa);
                        }
                    })
                } else {
                    alert("请选择需要导出的行!");
                }
            });
            $('#search').keyup(function () {
                jQuery(grid_selector).jqGrid('clearGridData');
                jQuery(grid_selector).jqGrid('setGridParam', {
                    postData: {"postData": $('#search').val()},
                    Page: 1
                }).trigger('reloadGrid');
                {#console.log($('#search').val())#}
            })
            $('#allexcel').click(function () {

                let rowNum = jQuery(grid_selector).jqGrid('getGridParam', 'rowNum')//每页的行数
                let total = jQuery(grid_selector).jqGrid('getGridParam', 'records')
                jQuery(grid_selector).jqGrid('setGridParam', {rowNum: total}).trigger('reloadGrid');

                setTimeout(function () {
                    var gr = jQuery(grid_selector).jqGrid("getDataIDs");
                    jQuery(grid_selector).jqGrid('setGridParam', {rowNum: rowNum}).trigger('reloadGrid');
                    var selectD = ''
                    for (var i = 0; i < gr.length; i++) { //保证同时可以删除多行
                        var ret = $(grid_selector).jqGrid("getRowData", gr[i]);
                        selectD = selectD + ret['_id'] + ",";
                    }
                    $.ajax({
                        url: "/wenjuan/ExportWenjuan/{{ request.user }}/no11/",
                        type: "POST",
                        data: {
                            selectRaw: selectD,
                            csrfmiddlewaretoken: '{{ csrf_token }}'
                        },
                        success: function (data) {
                            var aoa = [];
                            aoa.push(excelTitle);
                            for (var i = 0; i < JSON.parse(data).length; i++) {
                                aoa.push(JSON.parse(data)[i])
                            }
                            exportSpecialExcel(aoa);
                        }
                    })
                }, 100)
            });

            //replace icons with FontAwesome icons like above
            function updatePagerIcons(table) {
                var replacement =
                    {
                        'ui-icon-seek-first': 'icon-double-angle-left bigger-140',
                        'ui-icon-seek-prev': 'icon-angle-left bigger-140',
                        'ui-icon-seek-next': 'icon-angle-right bigger-140',
                        'ui-icon-seek-end': 'icon-double-angle-right bigger-140'
                    };
                $('.ui-pg-table:not(.navtable) > tbody > tr > .ui-pg-button > .ui-icon').each(function () {
                    var icon = $(this);
                    var $class = $.trim(icon.attr('class').replace('ui-icon', ''));
                    if ($class in replacement) icon.attr('class', 'ui-icon ' + replacement[$class]);
                })
            }

            function enableTooltips(table) {
                $('.navtable .ui-pg-button').tooltip({container: 'body'});
                $(table).find('.ui-pg-div').tooltip({container: 'body'});
            }

        });

        //下面代码为实现Excel导出功能
        //将一个sheet转成最终的excel文件的blob对象，然后利用URL.createObjectURL下载
        function sheet2blob(sheet, sheetName) {
            sheetName = sheetName || 'sheet1';
            var workbook = {
                SheetNames: [sheetName],
                Sheets: {}
            };
            workbook.Sheets[sheetName] = sheet;
            // 生成excel的配置项
            var wopts = {
                bookType: 'xlsx', // 要生成的文件类型
                bookSST: false, // 是否生成Shared String Table，官方解释是，如果开启生成速度会下降，但在低版本IOS设备上有更好的兼容性
                type: 'binary'
            };
            var wbout = XLSX.write(workbook, wopts);
            var blob = new Blob([s2ab(wbout)], {type: "application/octet-stream"});

            // 字符串转ArrayBuffer
            function s2ab(s) {
                var buf = new ArrayBuffer(s.length);
                var view = new Uint8Array(buf);
                for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
                return buf;
            }

            return blob;
        }

        /*
         * 通用的打开下载对话框方法，没有测试过具体兼容性
         * @param url 下载地址，也可以是一个blob对象，必选
         * @param saveName 保存文件名，可选
         */
        function openDownloadDialog(url, saveName) {
            if (typeof url == 'object' && url instanceof Blob) {
                url = URL.createObjectURL(url); // 创建blob地址
            }
            var aLink = document.createElement('a');
            aLink.href = url;
            aLink.download = saveName || ''; // HTML5新增的属性，指定保存文件名，可以不要后缀，注意，file:///模式下不会生效
            var event;
            if (window.MouseEvent) event = new MouseEvent('click');
            else {
                event = document.createEvent('MouseEvents');
                event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
            }
            aLink.dispatchEvent(event);
        }

        function exportSpecialExcel(aoa) {
            var sheet = XLSX.utils.aoa_to_sheet(aoa);
            openDownloadDialog(sheet2blob(sheet), '街道乡镇级基本信息记录.xlsx');
        }

    </script>

{% endblock %}
